package web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import web.misc.JsonHttpResponseWriter;
import web.servlet.dto.DtoFactory;

public class ExceptionFilter implements Filter {

    private JsonHttpResponseWriter jsonHandler;

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            jsonHandler.writeAsJson(DtoFactory.createErrorMessage("An error occurred while processing your request. Please try again later"), response);
        }
    }

    public void init(FilterConfig config) throws ServletException {
        this.jsonHandler = (JsonHttpResponseWriter) config.getServletContext().getAttribute("jsonHandler");
    }

}
